package com.elmcode.server.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.elmcode.server.exception.TokenException;
import com.elmcode.server.properties.JWTProperties;
import com.elmcode.server.utils.JWTUtil;
import com.elmcode.server.utils.Result;
import com.elmcode.server.vo.CustomerVo;
import com.elmcode.server.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private JWTProperties jwtProperties;

    public static ThreadLocal<CustomerVo> threadLocal = new ThreadLocal<>();


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /**
         * 怎么判断当前请求是否登录了呢？
         *   从请求投中获取token，然后判断是否有效
         */
        if(request.getMethod().equals(RequestMethod.OPTIONS.name())){
            return true;
        }
        String token = request.getHeader("token");
        if(!StringUtils.isEmpty(token)){
            Map<String, Object> map = null;
            try {
                map = JWTUtil.parseJWT(token, jwtProperties.getJwtKey());

                //TODO 针对user和customer做改进
                boolean customer = request.getRequestURI().contains("app");
                Object data = null;
                if(customer){
                    data = map.get(JWTUtil.CUSTOMER_ID);
                    CustomerVo customerVo = conservtData(data,new TypeReference<CustomerVo>(){});
                    threadLocal.set(customerVo);
                    log.info("{}顾客已经登录,信息为：{}",customerVo.getName(),customerVo);
                }else {
                    data = map.get(JWTUtil.USER_ID);
                    UserVo userVo = conservtData(data,new TypeReference<UserVo>(){});
                    log.info("{}商家已经登录,信息为：{}",userVo.getLoginName(),userVo);
                }

                return true;
            } catch (Exception e){
                throw new TokenException();
            }
        }else {
            //没有登录
            response.setContentType("application/json;charset=utf-8");
            PrintWriter writer = response.getWriter();

            Result<Object> result = new Result<>();
            result.setCode(500);
            result.setMsg("请登录");
            String respData = JSON.toJSONString(result);
            writer.print(respData);
            return false;
        }
    }

    private static <T> T conservtData(Object data, TypeReference<T> typeReference) {
        String s = JSON.toJSONString(data);
        T t = JSON.parseObject(s,typeReference);
        return t;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 当控制器方法调用结束，执行postHandle方法
        threadLocal.remove();
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
